package com.atguigu.yygh.msm.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONException;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.msm.config.ConstantPropertiesUtils;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.util.RandomUtil;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import org.springframework.stereotype.Service;

import javax.swing.text.html.FormSubmitEvent;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean send(MsmVo msmVo) {
        if(!StringUtils.isEmpty(msmVo.getPhone())) {
            String code = (String)msmVo.getParam().get("code");
            return this.send(msmVo.getPhone(),code);
        }
        return false;
    }

    private boolean send(String phone, Map<String,Object> param) {
        //判断手机号是否为空
        if(StringUtils.isEmpty(phone)) {
            return false;
        }
        return this.send(phone,"您下单了");
    }

    private boolean send(String phone , String code){
        try {
            code = RandomUtil.getSixBitRandom();
            String[] params = {code}; //短信中的参数
            SmsSingleSender ssender = new SmsSingleSender(
                    ConstantPropertiesUtils.APP_ID,
                    ConstantPropertiesUtils.APP_KEY);
            // 86 中国大陆  手机号码
            SmsSingleSenderResult result = ssender.sendWithParam("86",
                    phone, ConstantPropertiesUtils.TEMPLATE_ID,
                    params, "清风半月公众号", "", "");
            System.out.println(result);
            if (result.result == 0) {
                return true;
            }
        } catch (HTTPException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (com.github.qcloudsms.httpclient.HTTPException e) {
            e.printStackTrace();
        }
        return false;
    }

}
